#import <appkit/NXBitmapImageRep.h>
#import <streams/streams.h>
#import <appkit/tiff.h>

#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>

extern FILE *GIF_file;
extern unsigned char *r, *g, *b;
extern int GIF_xsize, GIF_ysize;

float factor = 120.0;
int verbose = 0;

int usec(struct timeval *t)
{
    return t->tv_sec * 1000 * 1000 + t->tv_usec;
}

int diff_time(struct timeval *s, struct timeval *e)
{
    return usec(e) - usec(s);
}

main(int argc, char *argv[])
{
	int i;
	struct timeval s, e;
	struct stat stat_buf;
	char *fname, *out;
	unsigned char *planes[3];
	id tiff;
	NXStream *file;

	for (i = 1; i < argc; i++)
	    if (argv[i][0] != '-')
	    	fname = argv[i];
	    else
		switch(argv[i][1]) {
		case 'v':
		    verbose = !verbose;
		    break;
		case 'f':
		    factor = atof(argv[++i]);
		    break;
		case 'o':
		    out = argv[++i];
		    break;
		case 'h':
		    fprintf(stderr,"usage: jpeg <gif-file> -o <tiff> "
		    	"[-f factor] [-v]\n");
		    exit(10);
		}
		
	if (fname == NULL) {
	    fprintf(stderr, "Error:  must specify input file.\n");
	    exit(10);
	}
	if (out == NULL) {
	    fprintf(stderr, "Error:  must specify output file.\n");
	    exit(10);
	}
	
	GIF_file = fopen(fname, "rb");
	stat(fname, &stat_buf);
	
	if (verbose)
	    printf("Starting size = %d.\n", stat_buf.st_size);
	i = stat_buf.st_size;
	
	gettimeofday(&s, NULL);
	if (readgifheader(stat_buf.st_size) < 0) {
	    fprintf(stderr, "Error:  bad header in %s.\n", fname);
	    exit(10);
	}
	if (readgif() < 0)
	    fprintf(stderr, "Error:  reading file %s... using what was "
	    "read.\n", fname);
	gettimeofday(&e, NULL);
	if (verbose)
	    printf("Time to read GIF = %d usec.\n", diff_time(&s, &e));
	
	gettimeofday(&s, NULL);
	planes[0] = r;
	planes[1] = g;
	planes[2] = b;
	tiff = [[NXBitmapImageRep alloc] initDataPlanes: planes 
		pixelsWide: (int) GIF_xsize
		pixelsHigh: (int) GIF_ysize bitsPerSample: 8
		samplesPerPixel: 3 hasAlpha: NO isPlanar: YES
		colorSpace: NX_RGBColorSpace bytesPerRow: GIF_xsize
		bitsPerPixel: 8];
	gettimeofday(&e, NULL);
	if (verbose)
	    printf("Time to convert = %d usec.\n", diff_time(&s, &e));

	gettimeofday(&s, NULL);
	file = NXOpenMemory(NULL, 0, NX_WRITEONLY);
	[tiff writeTIFF: file usingCompression: NX_TIFF_COMPRESSION_JPEG
		andFactor: factor];
	gettimeofday(&e, NULL);
	if (verbose)
	    printf("Time to JPEG = %d usec.\n", diff_time(&s, &e));

	NXSaveToFile(file, out);
	stat(out, &stat_buf);
	
	if (verbose)
	    printf("Ending size = %d.\n", stat_buf.st_size);
	if (verbose)
	    printf("Compression = %f%%\n", ((float) stat_buf.st_size) /
	    	((float) i) * 100.0);

}
